package com.self.cloudmall.oms.mq;

import com.rabbitmq.client.Channel;
import com.self.cloudmall.common.dto.SeckillOrderDto;
import com.self.cloudmall.oms.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RabbitListener(queues = "order.seckill.queue")
public class SeckillOrderMqHandler {

    @Autowired
    private OrderService orderService;

    @RabbitHandler
    private void handler(SeckillOrderDto seckillOrder, Message message, Channel channel){
        log.info("秒杀订单的订单号：{}",seckillOrder.getOrderSn());
        try {
            orderService.createSeckillOrder(seckillOrder);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            log.error("秒杀订单消息消费失败：{}",e);
            try {
                //拒绝签收消息，重新放入队列中
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            } catch (Exception ex) {
                log.error("秒杀订单拒绝签收异常：{}",ex);
            }
        }

    }
}
